package com.vf.framework.interceptor;

import com.alibaba.fastjson2.JSON;
import com.vf.common.constant.HttpStatus;
import com.vf.common.core.domain.AjaxResult;
import com.vf.common.core.domain.model.LoginUser;
import com.vf.common.utils.SecurityUtils;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


@Component
public class CheckLoginInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String uri = request.getRequestURI();
        if (uri.contains("login")){
            return true;
        }

        LoginUser loginUser = SecurityUtils.getLoginUser();
        if (loginUser == null){
            response.setStatus(HttpStatus.UNAUTHORIZED);
            response.setContentType("application/json/charset=utf-8");
            response.getWriter().write(JSON.toJSONString(AjaxResult.error(HttpStatus.UNAUTHORIZED,"请先登录")));
            return false;
        }
        return true;
    }
}
